package net.getbang.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import net.getbang.admin.entity.SysMenu;
import net.getbang.admin.mapper.SysMenuMapper;
import net.getbang.admin.mapper.SysUserMapper;
import net.getbang.admin.service.SysMenuService;
import net.getbang.common.Constant;
import net.getbang.common.Constant.MenuType;
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	@Autowired
	private SysMenuMapper sysMenuMapper;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public List<SysMenu> getUserMenuList(Long userId) {
		// 系统管理员，拥有最高权限
		if (userId == Constant.SUPER_ADMIN) {
			return getAllMenuList(null);
		}
		// 用户菜单列表
		List<Long> menuIdList = sysUserMapper.queryAllMenuId(userId);
		return getAllMenuList(menuIdList);
	}

	/**
	 * 获取所有菜单列表
	 */
	private List<SysMenu> getAllMenuList(List<Long> menuIdList) {
		// 查询根菜单列表
		List<SysMenu> menuList = queryListByParentId(0L, menuIdList);
		// 递归获取子菜单
		getMenuTreeList(menuList, menuIdList);

		return menuList;
	}

	/**
	 * 递归
	 */
	private List<SysMenu> getMenuTreeList(List<SysMenu> menuList, List<Long> menuIdList) {
		List<SysMenu> subMenuList = new ArrayList<SysMenu>();

		for (SysMenu entity : menuList) {
			if (entity.getType() == MenuType.CATALOG.getValue()) {// 目录
				entity.setList(getMenuTreeList(queryListByParentId(entity.getId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}

		return subMenuList;
	}

	@Override
	public List<SysMenu> queryListByParentId(Long parentId) {
		return sysMenuMapper.queryListByParentId(parentId);
	}

	@Override
	public List<SysMenu> queryListByParentId(Long parentId, List<Long> menuIdList) {
		List<SysMenu> menuList = queryListByParentId(parentId);
		if (menuIdList == null) {
			return menuList;
		}

		List<SysMenu> userMenuList = new ArrayList<>();
		for (SysMenu menu : menuList) {
			if (menuIdList.contains(menu.getId())) {
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}


	@Override
	public List<SysMenu> queryNotButtonList() {
		return sysMenuMapper.queryNotButtonList();
	}
}
